﻿using Furion;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Queer.AutoJob.Core.Entity;
using Queer.Util;
using Queer.Util.Helper;
using Queer.Util.Model;
using System;
using System.IO;
using System.Threading.Tasks;

namespace Queer.AutoJob
{
    public class DatabasesBackupJob : ITransient
    {
        private readonly IRepository<AutoJobEntity> _repository;

        public DatabasesBackupJob(IRepository<AutoJobEntity> repository)
        {
            _repository = repository;
        }

        public async Task<TData> Start()
        {
            string dbType = App.Configuration["ConnectionStrings:DBType"];
            if (dbType.ToLower() != "sqlserver")
                throw new Exception("暂不支持sqlserver以外的数据库执行备份");

            TData obj = new TData();
            string backupPath = GlobalContext.SystemConfig.DBBackup;

            if (string.IsNullOrWhiteSpace(backupPath))
                backupPath = Path.Combine(GlobalContext.HostingEnvironment.ContentRootPath, "Database");
            else
                backupPath = Path.Combine(GlobalContext.HostingEnvironment.ContentRootPath, backupPath);

            if (!Directory.Exists(backupPath))
                Directory.CreateDirectory(backupPath);

            await DatabaseBackup(backupPath);

            obj.Tag = 1;
            obj.Message = "备份路径：" + backupPath;
            return obj;
        }

        /// <summary>
        /// 执行备份
        /// </summary>
        /// <returns></returns>
        private async Task DatabaseBackup(string backupPath)
        {
            string database = HtmlHelper.Resove(App.Configuration["ConnectionStrings:DBConnectionString"].ToLower(), "initial catalog=", ";");
            string backupFile = string.Format("{0}\\{1}_{2}.bak", backupPath, database, DateTime.Now.ToString("yyyyMMddHHmmss"));
            string strSql = string.Format(" backup database [{0}] to disk = '{1}'", database, backupFile);

            await _repository.SqlNonQueryAsync(strSql);

        }
    }
}